//
//  BCUserNoSvipTitleCell.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/12/20.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCUserNoSvipTitleCell.h"

static CGFloat BCUserNoSvipTitleCellTopPadding = 30.0;
static CGFloat BCUserNoSvipTitleCellBottomPadding = 15.0;

@interface BCUserNoSvipTitleCell ()

@property (nonatomic, strong) UIImageView *titleIV;

@end

@implementation BCUserNoSvipTitleCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        //
        [self setupSubviews];
    }
    return self;
}

- (void)setupSubviews {
    self.titleIV = [UIImageView new];
    self.titleIV.contentMode = UIViewContentModeScaleAspectFit;
    [self.contentView addSubview:self.titleIV];
    [self.titleIV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.contentView).offset(BCUserNoSvipTitleCellTopPadding);
        make.centerX.mas_equalTo(self);
        make.width.mas_equalTo(0);
        make.height.mas_equalTo(0);
    }];
}




- (CGSize)sizeThatFits:(CGSize)size {
    CGFloat height = 0;
    height += BCUserNoSvipTitleCellTopPadding;
    //
    UIImage *image = [[SDImageCache sharedImageCache] imageFromCacheForKey:self.title];
    if (image) {
        CGSize titleIVSize = [self imageViewSizeFromImage:image maxSize:size];
        height += titleIVSize.height;
    }else {
        height += 46.0;//没有时默认加一个高度
    }
    height += BCUserNoSvipTitleCellBottomPadding;
    return CGSizeMake(size.width, height);
}

- (CGSize)imageViewSizeFromImage:(UIImage *)image maxSize:(CGSize)maxSize {
    CGSize imageSize = image.size;
    //
    CGFloat width = MIN(imageSize.width, maxSize.width*0.8);
    CGFloat height = width*(imageSize.height/imageSize.width);
    return CGSizeMake(width, height);
}

- (void)setTitle:(NSString *)title {
    _title = title;
    WEAK_SELF
    [self.titleIV sd_setImageWithURL:[NSURL URLWithString:title] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        [wself layoutTitleIV:image];
    }];
}

- (void)layoutTitleIV:(UIImage *)image {
    if (image) {
        [self layoutSubviews];
        [self.tableView beginUpdates];
        [self.tableView endUpdates];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    //
    CGSize titleIvSize = CGSizeZero;
    UIImage *image = [[SDImageCache sharedImageCache] imageFromCacheForKey:self.title];
    if (image) {
        titleIvSize = [self imageViewSizeFromImage:image maxSize:self.bounds.size];
    }
    [self.titleIV mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(titleIvSize.width);
        make.height.mas_equalTo(titleIvSize.height);
    }];
}

@end
